#include <fcntl.h>           
#include <sys/stat.h>        
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>

#define MAXLINE 100
#define CONTEXT "HELLO WORLD"
#define FILENAME "MY_FIFO"
#define LOOP 200
#define SEMRD "sem_read"
#define SEMWR "sem_write"

int main(int argc,char *argv[])
{
    /* create the named pipe fifo*/
    int fd;
    int ret;
    ret = mkfifo(FILENAME,0666);
    if(ret!=0)
    {
        perror("mkfifo");
    }
    fd=open(FILENAME,O_RDONLY);
    if(fd<0)
    {
        perror("open fifo");
    }
    /*open the semaphore*/
    sem_t *semwr,*semrd;
    int pwr,prd;
    semwr=sem_open(SEMWR,O_CREAT,0666,1);
    semrd=sem_open(SEMRD,O_CREAT,0666,0);
    if(semwr==(void*)-1 ||semrd==(void*)-1)
    {
        perror("sem_open failure");
    }
    printf("sem address\n");
    printf("semwr=%p\n",semwr);
    printf("semrd=%p\n",semrd);
    /*get this value*/
    sem_getvalue(semwr,&pwr);
    sem_getvalue(semrd,&prd);
    printf("wr value=%d\n",pwr);
    printf("rd value=%d\n",prd);
    /* communication period*/
    int i=LOOP;
    while (i--)
    {
        /*lock*/
        sem_wait(semrd);
        char recv[MAXLINE]={0};
        read(fd,recv,sizeof(recv));
        printf("read from my_fifo buf=[%s]\n",recv);
        sem_post(semwr);
    }
    /*close the file*/
    close(fd);
    sem_close(semwr);
    sem_close(semrd);
    /* release resource*/
    unlink(FILENAME);
    sem_unlink(SEMWR);
    sem_unlink(SEMRD);
    return 0;

}